const KoaJwt = require("koa-jwt");
const JwtToken = require("jsonwebtoken");

/**
 * jwt签名和校验方法集
 */
const AuthDefaultMethods = {
  //jwt 生成 token
  sigin: (payload, options = { expiresIn: "1h" }) => {
    const { expiresIn } = options;
    const token = JwtToken.sign({ payload }, config.jwtKey, { expiresIn });
    return token;
  },
  //jwt 校验 token (中间件默认调用)
  verify: (ctx, decodedToken, token) => {
    const { payload } = decodedToken;
    ctx.openid = payload;
    ctx.control = payload;
    return false;
  },
};

/**
 * jwt鉴权中间件
 * @param {[]}} unAuths
 */
const JwtMiddleWare = function ({ secret, verify, unAuths }) {
  return KoaJwt({
    secret,
    isRevoked: verify,
  }).unless({
    path: unAuths,
  });
};

module.exports = { JwtMiddleWare, AuthDefaultMethods };
